package com.leyou.upload.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.upload.config.OSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.net.www.content.image.gif;
import sun.net.www.content.image.jpeg;
import sun.net.www.content.image.png;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
public class UploadService {
    /**
     * 上传图片
     * 把图片保存到服务器上,要返回图片的路径
     * @param file
     * @return
     */
//    图片保存的路径
    private static final String  SAVE_PATH="D:\\class103\\sorfware\\nginx-1.16.0\\html\\brand-img\\";

//    图片返回的路径
    private static final String  RETURN_IMAGE_URL="http://image.leyou.com/brand-img/";


//    定义常见的图片mime类型
//    image/png  image/gif   image/jpeg
  private static final List<String> IMAGE_TYPE = Arrays.asList("image/png","image/gif","image/jpeg");
//    优化：1、只允许图片
//          2、防止假图片

    public String uploadImage(MultipartFile file) {
        try {
        String imageType = file.getContentType();//mime类型
        if(!IMAGE_TYPE.contains(imageType)){
//            类型错误
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
        BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
        if(bufferedImage==null){
//            表示是假图片
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
//        file.getOriginalFilename();图片的原名称  3.jpg
            String fileName = UUID.randomUUID() + file.getOriginalFilename();
            file.transferTo(new File(SAVE_PATH+fileName));
            return RETURN_IMAGE_URL+fileName;
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }

    }

    @Autowired
    private OSS client;

    @Autowired
    private OSSProperties properties;

    public Map<String, Object> signature() {
        try {
//            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + properties.getExpireTime() * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, properties.getMaxFileSize());
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, properties.getDir());

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            Map<String, Object> respMap = new LinkedHashMap<String, Object>();
            respMap.put("accessId", properties.getAccessKeyId()); //一定是accessId 官网上的是accessid
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", properties.getDir());
            respMap.put("host", properties.getHost());
            respMap.put("expire", expireEndTime); //毫秒 官网上的是秒
            return respMap;
        }catch (Exception e){
            throw new LyException(ExceptionEnum.INVALID_NOTIFY_SIGN);
        }
    }
}
